package com.android.dumiaogou.activity.mine;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.model.MainTabData;
import com.android.dumiaogou.model.data;
import com.android.dumiaogou.model.dataCallback;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.LoginState;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.dialog.MainMsg;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/11/3.
 */

public class OrderToShare extends TakePhotoActivity {
    @BindView(R.id.ll_orderdetail_goods_img)
    ImageView ll_orderdetail_goods_img;
    @BindView(R.id.ll_orderdetail_goods_title)
    TextView ll_orderdetail_goods_title;
    @BindView(R.id.ll_orderdetail_goods_price)
    TextView ll_orderdetail_goods_price;
    @BindView(R.id.ll_content_edit)
    EditText ll_content_edit;
    @BindView(R.id.item_item_detail_comment_star)
    RatingBar item_item_detail_comment_star;
    @BindView(R.id.order_grid_sort)
    NestFullListView order_grid_sort;

    private OrderToShare mcontext;
    private String need_id;
    String order_thumbs;
    String order_title;
    String order_price;

    private Gson gson = new Gson();
    private TakePhoto takePhoto;
    private MainMsg mdialog;
    private int mid;
    private ArrayList<MainTabData> griddata1 = new ArrayList<>();
    /**
     * 编辑
     */
    private ArrayList<String> mList = new ArrayList<>();
    private ArrayList<String> mList1 = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_ordertoshare);
        ButterKnife.bind(this);
        mcontext = OrderToShare.this;
        if (!LoginState.getInstance().getid(mcontext).equals("") && LoginState.getInstance().getid(mcontext) != null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
        }
        init();
    }

    private void init() {
        takePhoto = getTakePhoto();
        mdialog = new MainMsg(mcontext);
        item_item_detail_comment_star.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                ratingBar.setRating(v);
            }
        });
        mdialog.setOnSetCameraClickListener(new MainMsg.OnTaktPhotoClickListener() {
            @Override
            public void onClickCamera() {
                Uri uri = configCompress();
                takePhoto.onPickFromCapture(uri);
                mdialog.close();
            }

            @Override
            public void onClickGallery() {
                configCompress();
                int size = mList.size();
                takePhoto.onPickMultiple(1 - size);
                mdialog.close();
            }
        });
        griddata1.add(new MainTabData("添加图片", "0", ""));
        order_grid_sort.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_order_pic_add, griddata1) {
            @Override
            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                if (testBean.getId().equals("0")) {
                    holder.setVisible(R.id.present_ll, true);
                    holder.setVisible(R.id.select_ll, false);
                } else if (testBean.getId().equals(mList1.size() + 1 + "")) {
                    holder.setVisible(R.id.present_ll, true);
                    holder.setVisible(R.id.select_ll, false);
                    holder.setText(R.id.order_picnumber, testBean.getName());

                } else {
                    MyLog.e("iii3", testBean.getId() + "");
                    holder.setVisible(R.id.present_ll, false);
                    holder.setVisible(R.id.select_ll, true);
                    ObjectUtils.photo2(mcontext, testBean.getSrc(), ((ImageView) holder.getView(R.id.iv_adapter_grid_pic)));
                }
            }
        });
        order_grid_sort.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, final int i) {
                if (griddata1.get(i).getId().equals("0")) {
                    mdialog.show(mcontext.getWindow().getDecorView(), 1, null);
                } else if (griddata1.get(i).getId().equals(mList1.size() + 1 + "")) {
                    if (!griddata1.get(i).getId().equals("5")) {
                        mdialog.show(mcontext.getWindow().getDecorView(), 1, null);
                    }
                } else {
                    final MainMsg mainMsg = new MainMsg(mcontext);
                    mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否删除该照片？");
                    mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
                        @Override
                        public void onSure() {
                            mList1.remove(i);
                            griddata1.remove(i);
                            for (int j = i; j < griddata1.size(); j++) {
                                griddata1.get(j).setId(j + 1 + "");
                                if (j == griddata1.size() - 1) {
                                    griddata1.get(j).setName(mList1.size() + "/4");
                                }
                            }
                            if (mList1.size() == 0) {
                                griddata1.clear();
                                griddata1.add(new MainTabData("添加图片", "0", ""));
                            }
                            order_grid_sort.updateUI();
                            ObjectUtils.toast(mcontext, "删除成功");
                            mainMsg.close();

                        }
                    });

                }

            }
        });
        need_id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID);
        order_thumbs = getIntent().getStringExtra("order_thumbs");
        order_title = getIntent().getStringExtra("order_title");
        order_price = getIntent().getStringExtra("order_price");
        ObjectUtils.photo2(mcontext, order_thumbs, ll_orderdetail_goods_img);
        ll_orderdetail_goods_title.setText(order_title);
        ll_orderdetail_goods_price.setText(order_price);
    }

    //压缩
    private Uri configCompress() {
        File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_path) + System.currentTimeMillis() + ".png");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        CompressConfig config = new CompressConfig.Builder().setMaxSize(100 * 1024).setMaxPixel(1000).create();
        takePhoto.onEnableCompress(config, true);
        return imageUri;
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        ArrayList<TImage> images = result.getImages();
        mList.clear();
        mList.add(images.get(0).getCompressPath());
        upPic();
    }

    private void upPic() {
        if (mList.size() > 0) {
            boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBER_UPLOAD;
            if (networkConnected) {
                HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
                File file = new File(mList.get(0));
                HttpUtils.postfile(address, header, "upFile", file, upPicCallback);
            } else {
                ObjectUtils.toast(mcontext, "网络未连接");
            }
        }
    }

    dataCallback upPicCallback = new dataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.toast(mcontext, "上传失败");
        }

        @Override
        public void onResponse(data response, int id) {
            ObjectUtils.toast(mcontext, response.getMsg());
            if (response.getCode() == 0 && response.getData() != null) {
                mList1.add(response.getData());
                if (mList1.size() > 0) {
                    griddata1.clear();
                    for (int i = 0; i < mList1.size(); i++) {
                        griddata1.add(new MainTabData("", i + 1 + "", mList1.get(i)));
                    }
                    griddata1.add(new MainTabData(mList1.size() + "/4", mList1.size() + 1 + "", ""));
                    order_grid_sort.updateUI();
                } else {
                    griddata1.clear();
                    griddata1.add(new MainTabData("添加图片", "0", ""));
                    order_grid_sort.updateUI();
                }
            } else {
                if (response.getCode() == 40001) {
                    ObjectUtils.reLogin(mcontext);
                }
                if (mList1.size() == 0) {
                    griddata1.clear();
                    griddata1.add(new MainTabData("添加图片", "0", ""));
                    order_grid_sort.updateUI();
                }
            }
        }
    };

    @OnClick({R.id.release, R.id.main_top_back})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.release:
                String content = ll_content_edit.getText().toString().trim();
                if (content == null || content.equals("")) {
                    ObjectUtils.toast(mcontext, "请输入分享内容");
                    return;
                }
                int rate = (int) item_item_detail_comment_star.getRating();
                if (rate == 0) {
                    ObjectUtils.toast(mcontext, "请输入评分");
                    return;
                }
                if (mList1.size() <= 0) {
                    ObjectUtils.toast(mcontext, "请拍照上传");
                    return;
                }
                Claim(content, rate);
                break;
            case R.id.main_top_back:
                finish();
                break;
        }
    }

    private void Claim(String content, int rate) {
        if (mList1.size() > 0 && need_id != null) {
            boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
            String address = ConstantsUrl.domain + ConstantsUrl.ACUTION_COMMENT;
            if (networkConnected) {
                String thumbs = gson.toJson(mList1);
                HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
                HashMap<String, String> map = new HashMap<>();
                map.put("order_id", need_id);
                map.put("content", content);
                map.put("star", rate + "");
                map.put("thumbs", thumbs.toString());
                HttpUtils.post(address, header, map, upclaimCallback);
            } else {
                ObjectUtils.toast(mcontext, "网络未连接");
            }
        } else {
            ObjectUtils.toast(mcontext, "发布失败");
        }
    }

    dataCallback upclaimCallback = new dataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.toast(mcontext, "发布失败");
        }

        @Override
        public void onResponse(data response, int id) {
            MyLog.e("1q1", response.getCode() + "");
            ObjectUtils.toast(mcontext, response.getMsg());
            if (response.getCode() == 0) {
                mList1.clear();
                griddata1.clear();
                griddata1.add(new MainTabData("添加图片", "0", ""));
                order_grid_sort.updateUI();
                ll_content_edit.setText("");
                ObjectUtils.toast(mcontext, "发布成功");
            } else {
                if (response.getCode() == 40001) {
                    ObjectUtils.reLogin(mcontext);
                }
                ObjectUtils.toast(mcontext, "发布失败");
                if (mList1.size() == 0) {
                    griddata1.clear();
                    griddata1.add(new MainTabData("添加图片", "0", ""));
                    order_grid_sort.updateUI();
                }
            }
        }
    };

}